package cn.xsirl.websocket.util;

import cn.xsirl.websocket.message.ComponentMessage;

import java.nio.ByteBuffer;
import java.util.ArrayList;
import java.util.List;

/**
 * @version V1.0
 * @Title:
 * @ClassName: $PackageName$.$ClassName$.java
 * @Description:
 * @author: 谢明珑
 * @date: 2021/5/28$ 15:58$
 */
public class WebSocketUtil {
    /**
     * 解码
     *
     * 数据格式：
     *  ————————————————————————————————————————————————————————————
     * | 组件标识：2字节 | 消息类型：1字节 | 消息长度：4字节 | 消息内容 |
     * ————————————————————————————————————————————————————————————
     */
    public static List<ComponentMessage> decode(ByteBuffer buffer) {
        List<ComponentMessage> messages = new ArrayList<>();
        
        while(buffer.hasRemaining()) {
            short id = buffer.getShort();
            byte type = buffer.get();
            int length = buffer.getInt();
            byte[] content = new byte[length];
            buffer.get(content);
            
            messages.add(new ComponentMessage(id, type, content));
        }
        
        return messages;
    }
    
    /**
     * 编码
     * @param message
     * @return
     */
    public static ByteBuffer encode(ComponentMessage message) {
        
        byte[] componentId = BaseUtil.short2byte(message.getId());
        byte messageType = message.getType();
        byte[] messageContent = message.getContent();
        byte[] messageLength = BaseUtil.int2byte(messageContent.length);
        
        ByteBuffer buffer = ByteBuffer.allocate(2 + 1 + 4 + messageContent.length);
        buffer.put(componentId);
        buffer.put(messageType);
        buffer.put(messageLength);
        buffer.put(messageContent);
        
        // 重置buffer当前位置到开头
        buffer.rewind();
        
        return buffer;
    }
    
    /**
     * 拼接
     * @param buffers
     * @return
     */
    public static ByteBuffer concat(ByteBuffer ...buffers) {
        int length = 0;
        for (ByteBuffer buf : buffers) {
            length += buf.array().length;
        }
        byte[] bytes = new byte[length];
        int offset = 0;
        for (ByteBuffer buf : buffers) {
            byte[] array = buf.array();
            System.arraycopy(array, 0, bytes, offset, array.length);
            offset += array.length;
        }
        return ByteBuffer.wrap(bytes);
    }
}
